import { defineStore } from 'pinia'
import {
  login as loginApi,
  logout as logoutApi,
  Aimilogin as AimiloginApi
  // permCode,
  // userInfo
} from '/@/api/auth'
import {
  GetRoleFromID as GetRoleFromIDApi,
} from '/@/api/sys/role'
import { jwtDecode } from 'jwt-decode'

interface UserState {
  token?: string | undefined;
  aimitoken?: string | undefined;
  decode?: object | undefined;
  refresh_Token?: string | undefined;
  userId?: string;
  name?: string;
  userInfo?: any;
  ext?: any;
  roleId?: string;
  orgcode?: string;
  rolePermCode?: string
  // 用户权限标识
  permList?: Array<String>,
}
export const useUserStore = defineStore('app-user', {
  // 推荐使用 完整类型推断的箭头函数
  state: (): UserState => {
    return {
      // 所有这些属性都将自动推断其类型
      token: '',
      decode: {},
      refresh_Token: '',
      name: '',
      userId: '',
      userInfo: {},
      ext: {},
      permList: [],
      roleId: '',
      orgcode: '',
      rolePermCode: '',
      aimitoken: ''
    }
  },
  actions: {

    setToken(token: string | undefined) {
      this.token = token
    },
    setAimiToken(token: string | undefined) {
      this.aimitoken = token
    },
    setRefreshToken(refresh_Token: string | undefined) {
      this.refresh_Token = refresh_Token
    },
    setDecode(decode: object | undefined) {
      this.decode = decode
    },
    setRole(role: string | undefined) {
      this.roleId = role
    },
    setUser(role: string | undefined) {
      this.userId = role
    },
    setOrgCode(orgcode: string | undefined) {
      this.orgcode = orgcode
    },
    /**
     * 用户名密码登录
     * @param userName 
     * @param password 
     */
    login(user: string, password: string, timestamp: string): Promise<any> {
      let date = Number(new Date()).toString()
      return new Promise((resolve, reject) => {
        loginApi({
          user,
          password,
          timestamp: date
        }).then(res => {
          console.log('ok-login:', res);

          console.log('时间戳---', date);
          console.log('类型--', typeof date);


          if (res.errorcode === 0) {
            resolve(res.content)
            const decode = jwtDecode(res.content?.token)

            this.setToken(res.content?.token)
            this.setRefreshToken(res.content?.refresh_Token)
            this.setDecode(decode)
            this.setOrgCode((this.decode as any).OrgCode)
            this.setRole((this.decode as any).RoleId)
            this.setUser((this.decode as any).UserId)
            // this.roleId = (this.decode as any).RoleId
            // this.name = (this.decode as any).Name

            console.log('decode--', this.decode);

            console.log('token-ok!!', this.token);
            console.log('refresh_Token-ok!!', this.refresh_Token);

          } else {
            reject(new Error(res.msg || '登录失败'))
          }

        }).catch(e => {
          reject(e)
        })
      })
    },
    logout(): Promise<any> {
      return new Promise((resolve, reject) => {
        logoutApi({}).then(res => {
          resolve(res)
          this.clearUserCache()
        }).catch(e => {
          reject(e)
        })
      })
    },
    GetRole(data: string,): Promise<any> {
      return new Promise((resolve, reject) => {
        GetRoleFromIDApi({ roleID: data }).then(res => {
          this.rolePermCode = res.content.permissions;
          console.log(this.rolePermCode);
          
          resolve(res)

        }).catch(e => {
          reject(e)
        })
      })
    },
    GetAimiToken(email: string,password: string): Promise<any> {
      return new Promise((resolve, reject) => {
        AimiloginApi({ email,password}).then(res => {
          // this.rolePermCode = res.content.permissions;
          resolve(res)

        }).catch(e => {
          reject(e)
        })
      })
    },
    /**
     * 初始化权限标识
     */
  initPermCode() {

      if (this.getToken) {
         this.GetRole(this.getRole)
        // .then(
        //    res => {
        //     console.log('getRolePermCode----',res.content.permissions);
        //     // console.log('getRolePermCode',this.getRolePermCode);
        //     this.rolePermCode = res.content.permissions
        //     return this.permList?.push(this.getRolePermCode)
        //     // return this.permList?.push(this.getRolePermCode)
        //    }
        // )
        // console.log('getRolePermCode----');
        this.rolePermCode = 'administrator'
        
        return  this.permList?.push(this.getRolePermCode)

      }
      console.log('getRolePermCode',this.permList);
      // const menuStore = useMenuStore();
      //   menuStore.initMenu()

    },
    /**
     * 清理用户缓存
     */
    clearUserCache() {
      this.setToken(undefined)
      this.userId = undefined
      this.name = undefined
      this.permList = []
      this.userInfo = {}
    },
    /**
     * 判断是否有权限
     * @param code 权限code，多个使用英文逗号分割
     */
    hasPerm(code: string) {
      if (!code) {
        // code 未定义，则有权限
        return true
      }
      // admin===超级管理权限
      if (this.permList?.includes('administrator')) {
        console.log('administrator---');
        
        return true;
      }
      const codeArr: Array<String> = code.split(",")
      return this.permList?.some(item => {
        return codeArr.includes(item)
      })
    },
    getUserInfo() {
      //   return new Promise((resolve,reject)=>{
      if (this.getToken) {
        //       userInfo().then(res=>{
        //         resolve(res)
        return this.name = this.getName
        //         if(res.code === 0) {
        //           this.userId = res.data.id
        //           this.name = res.data.realName || res.data.userName
        //           this.userInfo = res.data
        //         }
        //       }).catch(e=>{
        //         reject(e)
        //       })
      }

      // else {
      //       resolve([])
      //     }
      //   })
    }
  },
  getters: {
    getToken(): string {
      return this.token || window.localStorage.getItem('token') || ''
    },
    getAimiToken(): string {
      return this.aimitoken || window.localStorage.getItem('token') || ''
    },
    getRefreshToken(): string {
      return this.refresh_Token || window.localStorage.getItem('refresh_Token') || ''
    },
    getName(): string {
      return this.name || ''
    },
    getUser(): string {
      return this.userId || ''
    },
    getRole(): string {
      return this.roleId || ''
    },
    getOrgCode(): string {
      return this.orgcode || ''
    },
    getRolePermCode(): string {
      return this.rolePermCode || ''
    },
  },
  persist: {
    storage: localStorage,
    key: "app-user"
  }
})